
package com.zhangyunfang.android.demo.custommenu;

import com.android.internal.view.menu.IconMenuItemView;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.LayoutInflater.Factory;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

public final class CustomMenu extends Activity {

    private static final String VIEW_ICON_MENU_ITEM = "com.android.internal.view.menu.IconMenuItemView";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        setMenuItemBackground();
        return super.onCreateOptionsMenu(menu);
    }

    private void setMenuItemBackground() {
        getLayoutInflater().setFactory(new Factory() {

            @Override
            public View onCreateView(String name, Context context, AttributeSet attrs) {
                if (name.equalsIgnoreCase(VIEW_ICON_MENU_ITEM)) {
                    try {
                        LayoutInflater f = getLayoutInflater();
                        final View view = f.createView(name, null, attrs);
                        new Handler().post(new Runnable() {
                            public void run() {
                                ((IconMenuItemView)view).setTextColor(getResources().getColorStateList(R.drawable.color_menu_text));
                                view.setBackgroundResource(R.drawable.bg_menu);
                            }
                        });
                        return view;
                    } catch (InflateException e) {
                    } catch (ClassNotFoundException e) {
                    }
                }
                return null;
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }
}
